<template>
  <div>
    <div class="detail-title">
      <div class="cicle">
      </div>
      {{ detailCar.numberPlate }}
      <img style="margin-right:0;margin-left:auto;cursor:pointer" :src="myRequire('map/popClose.png')"
        @click="closeDetailPage()">
    </div>
    <div style="border-top: 1px solid #EBEBEB; margin-top: -10px;width:100%;height: 10px;"></div>
    <el-tabs v-model="activeName" class="tabs" @tab-click="detailTabChange">
      <el-tab-pane v-for="v in filterDetailTabItem" :key="v.name" :label="v.label" :name="v.name"></el-tab-pane>
    </el-tabs>
    <div style="height:calc(100% - 150px)">
      <div class="detail-body" v-show="activeName == 'carInfo'">
        <div class="block-item">
          <div class="block-title">
            <div class="rectangle"></div>
            当前位置
          </div>
          <ul class="block-body">
            <li>
              <span>状态: {{ detailCar.vehicleStatus }}</span>
              <span>速度: {{ detailCar.spd }} km/h</span>
            </li>
            <li>
              卫星数: {{ detailCar.satelliteCount }}
            </li>
            <li>
              最后定位时间: {{ detailCar.gpsDateTime }}
            </li>
            <li>
              最后记录位置: {{ detailCar.location }}
            </li>
          </ul>
        </div>
        <div class="block-item">
          <div class="block-title">
            <div class="rectangle"></div>
            设备详情
          </div>
          <ul class="block-body">
            <li>
              <span>设备号: {{ detailCar.deviceNo }}</span>
              <span :title="detailCar.simId">sim卡号: {{ detailCar.simId }}</span>
            </li>
            <li>
              <span>监管类型: {{ detailCar.objTypeName }}</span>
              <span>设备型号: {{ detailCar.deviceModelStr }}</span>
              <!-- <span>设备品牌: {{ detailCar.vehicleBrand }}</span> -->
            </li>
            <li>
              <span>负责人: {{ detailCar.driverName }}</span>
              <span v-show="detailCar.objType == 0">设备颜色: {{ detailCar.vehicleColor }}</span>
            </li>
          </ul>
        </div>
        <div class="block-item">
          <div class="block-title" style="margin: 10px 0">
            <div class="rectangle"></div>
            IO信息
          </div>
          <ul class="io-dom">
            <li v-for="v in fliterCarRealStatusList" :key="v.prop">
              <img :src="getImgByParam(v.prop, detailCar[v.prop])" />
              <div class="img-text" :class="{ close: !detailCar[v.prop] }">{{ detailCar[v.prop] ? "开" : "关" }}
              </div>
              {{ v.name }}
            </li>
          </ul>
        </div>
        <div class="block-item">
          <div class="block-title">
            <div class="rectangle"></div>
            公司详情
          </div>
          <ul class="block-body">
            <li>
              <span :title="detailCar.companyName">所属公司: {{ detailCar.companyName }}</span>
            </li>
            <li>
              <span :title="detailCar.parentName">上级公司: {{ detailCar.parentName }}</span>
            </li>
            <li>
              <span>负责人: {{ detailCar.companyPerson }}</span>
              <span>联系电话: {{ detailCar.companyNumber }}</span>
            </li>
            <li>
              备注: {{ detailCar.remark }}
            </li>
          </ul>
        </div>
        <!-- echart和map -->
        <div class="block-item" style="height:250px">
          <div class="block-title">
            <div class="rectangle"></div>
            超速分析
          </div>
          <div style="height:calc(100% - 50px);width:100%">
            <LineChart echartsClass="normalLine" :echartsData='prop.spdLineData' ref="lineChart"></LineChart>
          </div>
        </div>
        <div class="block-item" style="height:250px">
          <div class="block-title">
            <div class="rectangle"></div>
            设备跟踪
          </div>
          <div style="height:calc(100% - 50px)" id="carDetailMap"></div>
        </div>
      </div>
      <div class="detail-body" v-show="activeName == 'orderSend'">
        <div class="order-top">
          <div class="block-title">
            <div class="rectangle"></div>
            指令类型
          </div>
          <ul style="height:calc(100% - 60px);width:100%;margin-top:10px">
            <li @click="sendOrder('文本信息下发')" v-hasPermi="['trajectoryMonitor:realtimePosition:textIssue']">
              <img :src="myRequire('map/order/textSend.png')" />
              <div>文本下发</div>
            </li>
            <li @click="sendOrder('疲劳驾驶(轨迹监控下发)')" v-hasPermi="['trajectoryMonitor:realtimePosition:fatigueDriving']">
              <img :src="myRequire('map/order/fatigueDriving.png')" />
              <div>疲劳驾驶</div>
            </li>
            <li @click="sendOrder('超速报警(轨迹监控下发)')" v-hasPermi="['trajectoryMonitor:realtimePosition:speedAlarm']">
              <img :src="myRequire('map/order/overspdAlarm.png')" />
              <div>超速报警</div>
            </li>
          </ul>
        </div>
        <div class="order-botm">
          <div class="block-title">
            <div class="rectangle"></div>
            指令下发记录
          </div>
          <div style="height:calc(100% - 115px);width:100%;">
            <el-table highlight-current-row ref="myTable" :data="tableData"
              :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }" height="100%">
              <el-table-column type="index" width="50" label="序号"></el-table-column>
              <el-table-column :prop="v.prop" :label="v.name" v-for="v in tableItems" :key="v.prop" :width="v.width"
                show-overflow-tooltip>
                <template #default="scope">
                  <span v-if='v.prop === "responseResult"'
                    :class="scope.row[v.prop] === '成功' ? 'success-tab' : 'failed-tab'">{{
                      scope.row[v.prop]
                    }}</span>
                  <span v-else-if='v.prop === "status"'
                    :style="{ color: (scope.row[v.prop].indexOf('成功') > -1 ? 'green' : 'red') }">{{
                      scope.row[v.prop]
                    }}</span>
                  <span v-else>{{ scope.row[v.prop] }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pagination">
            <pagination v-show="tablePagination.total > 0" :total="tablePagination.total"
              v-model:page="tablePagination.currentPage" v-model:limit="tablePagination.pageSize"
              @pagination="getTableData" />
            <!-- <el-pagination v-model:page-size="tablePagination.pageSize" v-model:current-page="tablePagination.currentPage"
              :total="tablePagination.total" :page-sizes="[15, 25, 50, 100]" background
              layout="total,sizes, prev, pager, next, jumper"></el-pagination> -->
          </div>
        </div>
      </div>
    </div>

    <!-- 指令下发窗体 -->
    <el-dialog :title="'指令下发-' + orderObj.orderName" draggable v-model="orderPageShow" width="480px"
      :destroy-on-close="true">
      <div class="body" style="max-height:320px;height:unset">
        <el-form :inline="true" v-for=" v  in  orderObj.confValue " :key="v.prop" label-width="120px">
          <el-form-item :label="v.name" :prop="v.prop">
            <!-- <el-input v-model="v.value"></el-input> -->
            <el-input v-if="v.type == 'noValue'" v-model="v.value" class="myInput" disabled></el-input>
            <el-select v-else-if="v.type == 'boolSelect'" v-model="v.value" class="myInput" :placeholder="'请选择' + v.name"
              filter>
              <el-option label="是" value="true"></el-option>
              <el-option label="否" value="false"></el-option>
            </el-select>
            <el-input-number v-else-if="v.type == 'numberInput'" v-model="v.value" :placeholder="'请输入数字'"
              class="myInput" />
            <el-input v-else v-model="v.value" class="myInput" :placeholder="'请输入' + v.name"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="orderSubmit">确 定</el-button>
          <el-button @click="closeOrderPage">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import dayjs from "dayjs"
import request from '@/utils/request'
import LineChart from "@/components/Echart/LineChart.vue"
import { hasPermissions } from "@/directive/permission/hasPermi"
import { watch } from 'vue';
import $store from "@/store/index";
const { proxy } = getCurrentInstance();
const tableData = ref([]);
const tableItems = ref([
  { name: '设备名称', prop: "vehicleNum" },
  { name: '指令类型', prop: "orderName" },
  { name: '指令内容', prop: "orderContent" },
  { name: '下发人', prop: "createUserName" },
  { name: '下发时间', prop: "sendTime", width: 160 },
  { name: '发送状态', prop: "statusName" },
  { name: '应答时间', prop: "responseTime", width: 160 },
  { name: '应答结果', prop: "responseResult" },
  { name: '失败原因', prop: "failReason" },
]);
const prop = defineProps({
  detailCar: { type: Object },
  spdLineData: { type: Object },
  closeDetailPage: { type: Function },
  resizeMap: { type: Function },
});
const { closeDetailPage } = prop;
const tablePagination = ref({
  total: 0,
  currentPage: 1,
  pageSize: 15,
});
const filterDetailTabItem = ref([]);
const detailTabItem = [
  { label: "设备详情", name: "carInfo", show: "carDetail" },
  { label: "指令下发", name: "orderSend", show: "orderSend" }
]
filterDetailTabItem.value = detailTabItem.filter(v => {
  return hasPermissions(['trajectoryMonitor:realtimePosition:' + v.show])
})
const activeName = ref(null);
if (filterDetailTabItem.value.length > 0) activeName.value = filterDetailTabItem.value[0].name;

const orderObj = ref({});//需要展示的指令对象
const orderPageShow = ref(false);
const orderCar = ref({});
const lineChart = ref();
const fliterCarRealStatusList = ref([]);
const carRealStatusList = [
  { prop: "acc", name: "acc", show: "acc" },
  { prop: "turnLeft", name: "左转", show: "turnLeft" },
  { prop: "turnRight", name: "右转", show: "turnRight" },
  { prop: "highBeam", name: "远光灯", show: "highBeam" },
  { prop: "dippedHeadlight", name: "近光灯", show: "entranceLight" },
  { prop: "oil", name: "油路", show: "oilCircuit" },
  { prop: "brake", name: "刹车", show: "brake" },
]
fliterCarRealStatusList.value = carRealStatusList.filter(v => {
  return hasPermissions(['trajectoryMonitor:realtimePosition:' + v.show])
})

// 获取设备的指令下发的表数据
function getTableData() {
  request({
    url: "/comlbs/orderSendRecord/device/list",
    method: "get",
    params: {
      deviceNo: prop.detailCar.deviceNo,
      startTime: dayjs(new Date()).add(-7, "days").format("YYYY-MM-DD HH:mm:ss"),
      endTime: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
      pageNum: tablePagination.value.currentPage,
      pageSize: tablePagination.value.pageSize,
      orderNames: "文本信息下发,疲劳驾驶(轨迹监控下发),超速报警(轨迹监控下发)",
    },
  }).then((res) => {
    if (res.code != 200) return
    tablePagination.value.total = res.total
    tableData.value = res.rows
  })
}
// 设备指令下发-第二个参数是设备树调用的时候传递的
function sendOrder(name, car) {
  request({
    url: "/comlbs/orderConfiguration/getConfigValue",
    method: "get",
    params: {
      orderName: name
    }
  }).then((res) => {
    if (res.code != 200) return
    orderPageShow.value = true;
    res.data?.confValue.forEach(v => {
      if (v.type == 'numberInput') v.value = Number(v.value)
    })
    orderObj.value = res.data
  })
  let _obj = car ?? prop.detailCar
  orderCar.value = {
    id: _obj.id,
    numberPlate: _obj.numberPlate,
    deviceId: _obj.deviceId,
  }
}
function myRequire(str) {
  return new URL(`../../../assets/img/${str}`, import.meta.url).href
}
function closeOrderPage() {
  orderPageShow.value = false
}
function detailTabChange(tab) {
  nextTick(() => {
    if (tab.props.name == 'carInfo') {
      nextTick(() => {
        lineChart.value.resize();
        prop.resizeMap();
      })
    }
  })
}
function getImgByParam(param, bool) {
  if (bool) {
    return myRequire(`map/detail/${param}-1.png`)
  } else {
    return myRequire(`map/detail/${param}.png`)
  }
}
// 设备指令提交
function orderSubmit() {
  let _orderObj = {
    "orderId": orderObj.value.id,//指令id
    "vehicleId": orderCar.value.id,//设备id
    "vehicleNum": orderCar.value.numberPlate,//设备名称
    "deviceNo": orderCar.value.deviceId,//设备id
    "confValue": orderObj.value.confValue,//配置的指令
    content: {
      "distributeMsgTopic": orderObj.value.orderType,//指令orderType
      "response": orderObj.value.response ? true : false,//指令response
      "userId": $store.state.value.user.info.userId,//用户id
      "userName": $store.state.value.user.info.userName,//账号
      "distributeTime": dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),//发出时间
      "devNo": orderCar.value.deviceId,//设备id
      "requestId": String(new Date().getTime() + 0)//自定义这条数据id
    }
  };
  orderObj.value.confValue.forEach((y) => {
    //如果字段需要时number类型则改为number
    if (GlobalSetting.numberPropList.indexOf(y.prop) !== -1) {
      y.value = Number(y.value)
    }
    //如果是农机指令需要传递items
    if (GlobalSetting.newOrders.indexOf(orderObj.value.orderType) === -1) {
      _orderObj.content[y.prop] = y.value;
    } else {
      if (_orderObj.content.items) _orderObj.content.items.push({ id: y.prop, value: y.value });
      else _orderObj.content.items = [{ id: y.prop, value: y.value }];
    }
  })
  request({
    url: "/comlbs/orderSendRecord",
    method: "post",
    data: [_orderObj],
  }).then((res) => {
    closeOrderPage();
    request({
      url: "/comlbs/orderSendRecord/sendOrder",
      method: "post",
      data: res.data,
    }).then(() => {
      proxy.$modal.msgSuccess("操作成功!");
      getTableData()
    })
  })
}

defineExpose({
  activeName,
  getTableData,
  tablePagination
})
</script>
<style lang='scss' scoped>
.tabs {
  :v-deep(.el-tabs__nav-wrap:after) {
    display: none;
  }
}

.myInput {
  width: 220px;
}

.detail-body {
  display: flex;
  width: 100%;
  height: 100%;
  overflow: auto;
  flex-wrap: wrap;
  justify-content: space-between;
  font-size: 14px;

  .order-top {
    width: 100%;
    min-width: 1180px;
    height: 160px;
    background: #f5f7fb;
    margin-bottom: 20px;
    box-sizing: border-box;
    padding: 0 20px;

    ul {
      li {
        display: inline-block;
        width: 60px;
        margin-right: 30px;
        margin-bottom: 5px;
        text-align: center;
        color: #424242;
        position: relative;
        cursor: pointer;

        &:last-of-type {
          margin-right: 0;
        }

        img {
          width: 100%;
        }
      }
    }
  }

  .order-botm {
    height: calc(100% - 180px);
    width: 100%;
    min-width: 1140px;
    background: #f5f7fb;
    padding: 0 20px;
    position: relative;

    .pagination {
      position: absolute;
      right: 20px;
      bottom: 0;

      .pagination-container {
        background-color: unset;
      }
    }
  }

  .block-item {
    width: 49.5%;
    min-width: 420px;
    height: 180px;
    background: #f5f7fb;
    box-sizing: border-box;
    padding: 0 15px;
    margin-bottom: 10px;

    .img-text {
      position: absolute;
      right: -5px;
      bottom: 15px;
      z-index: 5;
      width: 20px;
      height: 20px;
      border-radius: 10px;
      color: #fffef8;
      background-color: #00df29;

      &.close {
        color: #84919e;
        background-color: #eee;
      }
    }

    .block-body {
      color: #424242;

      li {
        display: flex;
        margin-bottom: 10px;

        span {
          flex: 1;
          margin-right: 10px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;

          &:last-of-type {
            margin: 0;
          }
        }
      }
    }

    .io-dom {
      display: flex;
      justify-content: space-around;

      li {
        display: inline-block;
        width: 50px;
        margin-bottom: 10px;
        text-align: center;
        color: #424242;
        position: relative;

        img {
          width: 100%;
        }
      }
    }
  }

  .block-title {
    color: #424242;
    font-size: 16px;
    font-weight: 600;
    height: 50px;
    display: inline-flex;
    align-items: center;
  }
}

.detail-title {
  font-weight: 600;
  font-size: 24px;
  color: #424242;
  height: 80px;
  display: flex;
  align-items: center;

  //通用-蓝色双圆
  .cicle {
    width: 10px;
    height: 10px;
    background-color: #0066FF;
    border-radius: 20px;
    border: 10px solid rgb(217, 232, 255);
    display: inline-block;
    margin-right: 10px;
    box-sizing: unset;
  }
}

:deep(.el-table) {
  border: 0 !important;
}
</style>